package com.it.schoolbookshop_back.task;

import com.it.schoolbookshop_back.entities.po.Transaction;
import com.it.schoolbookshop_back.enums.OrderStatusEnum;
import com.it.schoolbookshop_back.mapper.OrderMapper;
import com.it.schoolbookshop_back.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单超时取消定时任务
 */
@Slf4j
@Component
public class OrderTimeoutTask {
    
    /**
     * 订单超时时间（分钟）
     */
    private static final int ORDER_TIMEOUT_MINUTES = 30;
    
    /**
     * 日期时间格式化器，用于解析数据库返回的日期时间
     */
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.S]");
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 每5分钟执行一次的定时任务，检查并取消超时未支付的订单
     */
    @Scheduled(fixedRate = 5 * 60 * 1000) // 每5分钟执行一次
    public void checkAndCancelTimeoutOrders() {
        log.info("开始检查超时未支付订单...");
        
        try {
            // 查询所有pending状态的订单
            List<Map<String, Object>> pendingOrders = orderMapper.getAllOrders(OrderStatusEnum.PENDING.getStatus());
            
            if (pendingOrders.isEmpty()) {
                log.info("没有待处理的订单，本次检查结束");
                return;
            }
            
            log.info("检测到 {} 个待处理订单", pendingOrders.size());
            LocalDateTime now = LocalDateTime.now();
            
            for (Map<String, Object> order : pendingOrders) {
                try {
                    String orderId = (String) order.get("order_id");
                    Object createdAtObj = order.get("created_at");
                    
                    if (createdAtObj == null) {
                        log.warn("订单 {} 没有创建时间，跳过处理", orderId);
                        continue;
                    }
                    
                    LocalDateTime createdAt;
                    if (createdAtObj instanceof LocalDateTime) {
                        createdAt = (LocalDateTime) createdAtObj;
                    } else {
                        // 使用自定义格式化器解析日期时间字符串
                        try {
                            createdAt = LocalDateTime.parse(createdAtObj.toString(), DATE_TIME_FORMATTER);
                        } catch (DateTimeParseException e) {
                            log.warn("无法解析订单 {} 的创建时间: {}，尝试使用标准解析", orderId, createdAtObj);
                            // 如果自定义格式解析失败，尝试使用标准解析（兜底方案）
                            createdAt = LocalDateTime.parse(createdAtObj.toString());
                        }
                    }
                    
                    // 计算订单创建到现在的时间差
                    long minutesElapsed = ChronoUnit.MINUTES.between(createdAt, now);
                    
                    // 如果超过了设定的超时时间，则取消订单
                    if (minutesElapsed >= ORDER_TIMEOUT_MINUTES) {
                        log.info("订单 {} 已超时 {} 分钟，开始取消", orderId, minutesElapsed);
                        boolean result = orderService.cancelOrder(orderId);
                        if (result) {
                            log.info("订单 {} 已成功取消", orderId);
                        } else {
                            log.warn("订单 {} 取消失败", orderId);
                        }
                    }
                } catch (Exception e) {
                    log.error("处理订单 {} 时出错: {}", order.get("order_id"), e.getMessage(), e);
                }
            }
            
            log.info("超时订单检查完成");
        } catch (Exception e) {
            log.error("检查超时订单时出错: {}", e.getMessage(), e);
        }
    }
} 